package Pet.Management.service.impl;

import Pet.Management.domain.entity.TaskNode;
import Pet.Management.repository.TaskNodeRepository;
import Pet.Management.service.TaskNodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Service
public class TaskNodeServiceImpl implements TaskNodeService {

    private static final Logger logger = LoggerFactory.getLogger(TaskNodeServiceImpl.class);

    @Autowired
    private TaskNodeRepository taskNodeRepository;

    @Override
    public List<TaskNode> getTaskNodesByOrderId(Long orderId) {
        return taskNodeRepository.findByOrderIdOrderByNodeOrder(orderId);
    }
    
    @Override
    public Optional<TaskNode> getTaskNodeById(Long id) {
        return taskNodeRepository.findById(id);
    }
    
    @Override
    @Transactional
    public TaskNode createTaskNode(TaskNode taskNode) {
        taskNode.setCreateTime(LocalDateTime.now());
        taskNode.setUpdateTime(LocalDateTime.now());
        if (taskNode.getStatus() == null) {
            taskNode.setStatus(0); // 设置初始状态为待完成
        }
        return taskNodeRepository.save(taskNode);
    }
    
    @Override
    @Transactional
    public TaskNode updateTaskNode(TaskNode taskNode) {
        logger.info("Updating task node with ID: {}", taskNode.getId());
        TaskNode existingNode = taskNodeRepository.findById(taskNode.getId())
                .orElseThrow(() -> new RuntimeException("Task node not found"));
        
        // 只更新非空字段，保留原有的必填字段
        if (taskNode.getTitle() != null) {
            existingNode.setTitle(taskNode.getTitle());
        }
        
        if (taskNode.getDescription() != null) {
            existingNode.setDescription(taskNode.getDescription());
        }
        
        if (taskNode.getStatus() != null) {
            existingNode.setStatus(taskNode.getStatus());
        }
        
        // 处理二进制图片数据
        if (taskNode.getProofImage() != null && taskNode.getProofImage().length > 0) {
            try {
                existingNode.setProofImage(taskNode.getProofImage());
                logger.info("Set binary image data, length: {} bytes", taskNode.getProofImage().length);
            } catch (Exception e) {
                logger.error("Error processing image data", e);
                // 继续处理其他字段，不让图片处理错误影响整体操作
            }
        } else {
            logger.debug("No image data provided or empty data");
        }
        
        // 处理mediaUrls字段 - 如果有提供，则更新
        if (taskNode.getMediaUrls() != null) {
            existingNode.setMediaUrls(taskNode.getMediaUrls());
            logger.info("Updated mediaUrls field: {}", taskNode.getMediaUrls());
        }
        
        if (taskNode.getProofDescription() != null) {
            existingNode.setProofDescription(taskNode.getProofDescription());
        }
        
        // 处理proof_text字段
        if (taskNode.getProofText() != null) {
            existingNode.setProofText(taskNode.getProofText());
        }
        
        existingNode.setUpdateTime(LocalDateTime.now());
        logger.info("Task node update prepared, saving changes");
        
        return taskNodeRepository.save(existingNode);
    }
    
    @Override
    @Transactional
    public void deleteTaskNode(Long id) {
        taskNodeRepository.deleteById(id);
    }

    @Override
    @Transactional
    public TaskNode completeTaskNode(Long id) {
        TaskNode taskNode = taskNodeRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("Task node not found"));
        taskNode.setStatus(1); // 设置为已完成状态
        taskNode.setCompleteTime(LocalDateTime.now());
        taskNode.setUpdateTime(LocalDateTime.now());
        return taskNodeRepository.save(taskNode);
    }
    
    @Override
    @Transactional
    public List<TaskNode> saveAllTaskNodes(List<TaskNode> taskNodes) {
        LocalDateTime now = LocalDateTime.now();
        taskNodes.forEach(node -> {
            if (node.getCreateTime() == null) {
                node.setCreateTime(now);
            }
            node.setUpdateTime(now);
            node.setStatus(0); // 默认为待处理状态
        });
        return taskNodeRepository.saveAll(taskNodes);
    }
    
    @Override
    @Transactional
    public TaskNode updateTaskNodeStatus(Long id, Integer status) {
        TaskNode taskNode = taskNodeRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("Task node not found"));
        
        taskNode.setStatus(status);
        taskNode.setUpdateTime(LocalDateTime.now());
        
        return taskNodeRepository.save(taskNode);
    }
    
    @Transactional
    public TaskNode confirmTaskNode(Long nodeId) {
        TaskNode node = taskNodeRepository.findById(nodeId)
                .orElseThrow(() -> new RuntimeException("Task node not found"));

        // Check if node can be confirmed
        if (node.getStatus() != 1) {
            throw new RuntimeException("Task node must be completed before confirmation");
        }

        // Update status to confirmed (2)
        node.setStatus(2);
        node.setUpdateTime(LocalDateTime.now());

        // Save changes
        return taskNodeRepository.save(node);
    }

    @Override
    public boolean isOrderCompleted(Long orderId) {
        return taskNodeRepository.countUnconfirmedNodes(orderId) == 0;
    }

    @Override
    public List<TaskNode> getPendingNodes(Long orderId) {
        return taskNodeRepository.findPendingNodesByOrderId(orderId);
    }

    @Override
    @Transactional
    public List<TaskNode> createInitialTaskNodes(Long orderId) {
        // 创建默认的三个任务节点
        TaskNode node1 = new TaskNode();
        node1.setOrderId(orderId);
        node1.setNodeOrder(1);
        node1.setTitle("接收宠物");
        node1.setDescription("检查宠物状态，确认物品清单");
        node1.setStatus(0);
        node1.setCreateTime(LocalDateTime.now());
        node1.setUpdateTime(LocalDateTime.now());

        TaskNode node2 = new TaskNode();
        node2.setOrderId(orderId);
        node2.setNodeOrder(2);
        node2.setTitle("日常照顾");
        node2.setDescription("按时喂食、清理、陪伴玩耍");
        node2.setStatus(0);
        node2.setCreateTime(LocalDateTime.now());
        node2.setUpdateTime(LocalDateTime.now());

        TaskNode node3 = new TaskNode();
        node3.setOrderId(orderId);
        node3.setNodeOrder(3);
        node3.setTitle("返还宠物");
        node3.setDescription("确认宠物状态，整理托管报告");
        node3.setStatus(0);
        node3.setCreateTime(LocalDateTime.now());
        node3.setUpdateTime(LocalDateTime.now());

        return taskNodeRepository.saveAll(Arrays.asList(node1, node2, node3));
    }
} 